package org.example.job;

import lombok.RequiredArgsConstructor;
import org.example.domain.entity.Article;
import org.example.domain.entity.City;
import org.example.domain.entity.Spot;
import org.example.service.ArticleService;
import org.example.service.CityService;
import org.example.service.SpotService;
import org.example.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class UpdateViewCountJob {

    private final RedisCache redisCache;

    private final ArticleService articleService;

    private final SpotService spotService;

    private final CityService cityService;

    @Scheduled(cron = "* 0/10 * * * ?")
    public void updateViewCount(){

        Map<String, Integer> articleViewCount = redisCache.getCacheMap("ArticleViewCount");

        Map<String, Integer> spotViewCount = redisCache.getCacheMap("SpotViewCount");

        Map<String, Integer> cityViewCount = redisCache.getCacheMap("CityViewCount");

        List<Article> articles = articleViewCount.entrySet()
                .stream().map(entry -> new Article(Integer.valueOf(entry.getKey()), entry.getValue()))
                .collect(Collectors.toList());

        List<Spot> spots = spotViewCount.entrySet().stream().map(entry -> new Spot(Integer.valueOf(entry.getKey()), entry.getValue()))
                .collect(Collectors.toList());

        List<City> cities = cityViewCount.entrySet().stream().map(entry -> new City(Integer.valueOf(entry.getKey()),entry.getValue()))
                        .collect(Collectors.toList());

        articleService.updateBatchById(articles);
        spotService.updateBatchById(spots);
        cityService.updateBatchById(cities);

    }

}
